<template>
  <el-container>
    <!--       aside -->
    <!--      100vh为整个窗口高度-->
    <el-aside style="width:200px; min-height: 1000px;background-color: #15293b">
      <div style="height: 60px; color: aliceblue; display: flex; align-items: center;justify-content: center" >
        <img :src="require('@/assets/library.jpg')" style="height: 80%;">
      </div>
      <!--        侧边导航栏-->

      <el-menu style="border: none" :default-active="$route.path" router background-color="#15293b" text-color="rgba(255,255,255,0.65)" active-text-color="#FFF" @select="handleSelect">
        <el-menu-item index="/login">
          <template slot="title">
            <i class="el-icon-right"></i>
            <span>登录界面</span>
          </template>
        </el-menu-item>
        <el-menu-item index="/home">
          <template slot="title">
            <i class="el-icon-s-marketing"></i>
            <span>系统首页</span>
          </template>
        </el-menu-item>
        <el-menu-item index="/about">
          <template slot="title">
            <i class="el-icon-user"></i>
            <span>用户管理</span>
          </template>
        </el-menu-item>
        <el-menu-item index="/product">
          <template slot="title">
            <i class="el-icon-collection"></i>
            <span>书籍管理</span>
          </template>
        </el-menu-item>
        <el-submenu>
          <template slot="title">
            <i class="el-icon-loading"></i>
            <span></span>
          </template>
        </el-submenu>
      </el-menu>
    </el-aside>


    <el-container>
      <!-- header -->
      <el-header style="display: flex; align-items: center; justify-content: space-between; height: 60px; background-color: #2c3e50; color: white;">
        <div style="text-align: center; width: 100%;">图书管理系统</div>
        <el-tooltip class="item" effect="dark" content="新消息" placement="top" style="margin-right: 40px">
          <el-badge  class="item">
            <el-button @click="notice()" size="mini" type="primary" icon="el-icon-message-solid" circle></el-button>
          </el-badge>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="个人中心" placement="top" style="margin-right: 20px">
          <el-badge  class="item">
            <el-button @click="personCenter()" size="mini" type="primary" icon="el-icon-user-solid" circle></el-button>
          </el-badge>
        </el-tooltip>
      </el-header>

      <!-- main -->
      <el-main>
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">

          <el-form-item >
            <el-input v-model="searchForm.bookname" placeholder="搜索书籍" prefix-icon="el-icon-search"></el-input>
          </el-form-item>
          <el-form-item >
            <el-select v-model="searchForm.category" placeholder="类别" @onclick="getAllCategorys" >
              <!-- 假设 categorys 数组的每个元素都是一个包含类别名称的字符串 -->
              <el-option v-for="category in categorys" :key="category" :label="category" :value="category" ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item style="margin-top: 10px">
            <el-button type="primary" @click="onSubmit()">查询</el-button>
          </el-form-item>
          <el-form-item style="margin-top: 10px">
            <el-button type="primary" @click="update()">刷新</el-button>
          </el-form-item >
          <el-button type="success" round style="margin-left: 60px;margin-top: 10px" @click="createBook">上传书籍</el-button>
        </el-form>

        <el-dialog title="书籍信息" :visible.sync="dialogFormVisible2">
          <el-form label-width="100px" size="small">
            <!--                  编辑对话框-->
            <el-form-item label="bookname" >
              <el-input v-model="createData.bookname" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="author" >
              <el-input v-model="createData.author" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="category" >
              <el-input v-model="createData.category" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="价格" >
              <el-input v-model="createData.price" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="出版社" >
              <el-input v-model="createData.press" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="余量" >
              <el-input v-model="createData.surplus" autocomplete="off"></el-input>
            </el-form-item>
            <div style="align-items: center; justify-content: center; display: flex">
              <h3>上传封面：</h3>
              <el-upload
                  class="avatar-uploader"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
            <!--                  编辑对话框-->
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible2 = false">取 消</el-button>
            <el-button type="primary" @click="uploadBook()">确 定</el-button>
          </div>
        </el-dialog>

        <el-table :data="tableData" border>
<!--          <el-table-column prop="bookid" label="bookid" width="160">-->
<!--          </el-table-column>-->
          <el-table-column prop="bookname" label="书籍" width="250" align="center">
          </el-table-column>
          <el-table-column prop="author" label="作者" width="200" align="center">
          </el-table-column>
          <el-table-column prop="category" label="类别" width="200" align="center">
          </el-table-column>
          <el-table-column prop="press" label="出版社" width="200" align="center">
          </el-table-column>
          <el-table-column prop="price" label="价格" width="200" align="center">
          </el-table-column>
          <el-table-column prop="surplus" label="余量" width="200" align="center">
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="updateBook(scope.row.bookname)" style="margin-right: 15px;">编辑</el-button>
              <el-dialog title="书籍信息" :visible.sync="dialogFormVisible">
                <el-form label-width="100px" size="small">
                  <!--                  编辑对话框-->
                  <el-form-item label="bookname" >
                    <el-input v-model="updateData.bookname" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="author" >
                    <el-input v-model="updateData.author" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="category" >
                    <el-input v-model="updateData.category" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="价格" >
                    <el-input v-model="updateData.price" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="出版社" >
                    <el-input v-model="updateData.press" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="余量" >
                    <el-input v-model="updateData.surplus" autocomplete="off"></el-input>
                  </el-form-item>

                  <!--                  编辑对话框-->
                </el-form>
                <div slot="footer" class="dialog-footer">
                  <el-button @click="dialogFormVisible = false">取 消</el-button>
                  <el-button type="primary" @click="updateComfirm()">确 定</el-button>
                </div>
              </el-dialog>

            <el-button @click="showDeleteConfirm(scope.row.bookid)" size="mini" type="danger">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <br>
        <el-pagination
            background
            layout=" prev, pager, next, total" @current-change="handleCurrentChange"
            :total="itemNumber" :current-page="currentPage" :page-size="pageSize">
        </el-pagination>

      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import axios from 'axios';
import Cookies from "js-cookie";
export default {
  data() {
    return {
      imageUrl: '',
      username:'',
      password:'',
      fullData: [], // 存储从服务器获取的所有数据
      tableData: [],
      updateData: [],
      categorys: [],
      createData:[],
      itemNumber:1,
      Jwt:"",
      is_admin:false,
      dialogFormVisible:false,
      dialogFormVisible2:false,
      currentPage: 1,
      pageSize: 10,
      fileRaw: null,
      searchForm: {
        bookname: '',
        category: ''
      }
    }
  },
  methods:{

    notice(){
      if(!this.is_admin){
        this.$router.push({ name: 'notice'});
      }
      else {
        this.$router.push({ name: 'adminnotice'});
      }
    },
    personCenter(){
      const message = "this is admin";
      this.$router.push({ name: 'person', params: { message }});
    },
    uploadBook() {
      this.dialogFormVisible2 = false;

      // 创建一个 FormData 对象
      const formData = new FormData();
      console.log("sadw"+this.fileRaw)
      // 将书籍信息添加到 FormData 中
      formData.append('bookname', this.createData.bookname);
      formData.append('author', this.createData.author);
      formData.append('press', this.createData.press);
      formData.append('surplus', this.createData.surplus);
      formData.append('category', this.createData.category);
      formData.append('price', this.createData.price);
      // 将文件添加到 FormData 中
      formData.append('avatar', this.fileRaw);

      axios.post('http://127.0.0.1:5000/v1/admin/addBook', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'token': Cookies.get('token')
        }
      })
          .then(() => {
            this.getAllCategorys();
            this.update();
            this.createData = {};
            this.$message({
              type: 'success',
              message: '上传成功'
            });
          })
          .catch(error => {
            console.error('Error:', error);
          });
    },
    updateComfirm(){
      this.dialogFormVisible = false;
      axios.put('http://127.0.0.1:5000/v1/admin/editBookInfo',
          {  bookid:this.updateData.bookid,
                  bookname:this.updateData.bookname,
                  author:this.updateData.author,
                  press:this.updateData.press,
                  surplus:this.updateData.surplus,
                  category:this.updateData.category ,
                  price:this.updateData.price,

          },
          { headers: { 'Content-Type': 'application/json', 'token': Cookies.get('token')} }
      )
          .then(() => {
              this.update();
              this.getAllCategorys();
            this.$message({
              type: 'success',
              message: '更新成功'
            });
          })
          .catch(error => {
            console.error('Error:', error);
          });
    },
    createBook(){
      this.dialogFormVisible2 = true;
    },
    updateBook(bookName) {
      this.dialogFormVisible = true;
      axios.post('http://127.0.0.1:5000/v1/books/getBookByName',
          { bookname: bookName },
          { headers: { 'Content-Type': 'application/json' } }
      )
          .then(response => {
            if (response.data.data.length > 0) {
              this.updateData = response.data.data[0]; // 取第一本书
              // alert(this.updateData.bookname); // Alert the bookname of the first book
            } else {
              alert("No books found");
            }
          })
          .catch(error => {
            console.error('Error:', error);
          });
    },
    update(){
      this.getAllCategorys();
      // 发送异步请求获取数据
      axios.get("http://127.0.0.1:5000/v1/books/allBooks").then((result)=> {
        this.fullData = result.data.data;

        // 更新当前页为第一页
        this.currentPage = 1;
        // 计算当前页的数据范围
        const start = (this.currentPage - 1) * this.pageSize;
        const end = start + this.pageSize;
        // 更新显示用的表格数据
        this.tableData = this.fullData.slice(start, end);

        // 重置搜索表单
        this.searchForm.category = '';
        this.searchForm.bookname = '';
        this.itemNumber = this.fullData.length;
      });
    },
    showDeleteConfirm(bookid) {
      this.$confirm('此操作将永久删除该书籍, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户点击确定后执行删除操作
        this.deleteBook(bookid);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    deleteBook(bookid) {
      axios.delete(`http://127.0.0.1:5000/v1/admin/deleteBook/${bookid}`)
          .then(() => {
            this.$message({
              type: 'success',
              message: '删除成功'
            });
            if(this.tableData.length==1)
            {
              this.currentPage = this.currentPage - 1;
            }
            this.update();
            this.getAllBooks(); // 成功删除后调用，更新数据
            this.getAllCategorys(); // 假设你需要在书籍删除成功后更新分类
          })
          .catch(error => {
            this.$message({
              type: 'error',
              message: '删除失败'
            });
            console.error("Error deleting book:", error.response);
          });
    },
    onSubmit() {
      const { category, bookname } = this.searchForm;

      if (category !== '' || bookname !== '') {
        let url = 'http://127.0.0.1:5000/v1/books/';
        let data = {};

        if (category && bookname) {
          url += 'getBooksByNameAndCategory';
          data = { category, bookname };
        } else if (category) {
          url += 'getBooksByCategory';
          data = { category };
        } else if (bookname) {
          url += 'getBookByName';
          data = { bookname };
        }

        axios.post(url, data, {
          headers: {'Content-Type': 'application/json'}
        }).then(response => {
          this.fullData = response.data.msg === "success" ? response.data.data : [];
          this.updateTableData();
        }).catch(error => {
          alert("无该书籍");
          console.error('Error:', error);
        });
      } else {
        alert("输入为空");
      }
    },
    updateTableData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.tableData = this.fullData.slice(start, end);
      this.itemNumber = this.fullData.length;
    },


    getAllCategorys(){
      axios.get("http://127.0.0.1:5000/v1/books/getAllCategories").then((result)=> {
        // 假设result.data.data是一个包含所有类别的数组
        this.categorys = result.data.data;
        // this.searchForm.category = this.categorys[0];
      }).catch(error => {
        console.error("Error fetching categories:", error);
      });
    },
    getAllBooks(){
      this.getFull();
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.tableData = this.fullData.slice(start, end);
    },
    getAllBooks1(){
      axios.get("http://127.0.0.1:5000/v1/books/allBooks").then((result)=> {
        this.fullData = result.data.data;
      });
    },

    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.getFull();
    },
    getFull() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.tableData = this.fullData.slice(start, end);
    },
    handleAvatarSuccess(res, file) {
      console.log('111111')
      // const bookname = this.createData.bookname
      this.fileRaw = file.raw;
      this.imageUrl = URL.createObjectURL(file.raw);
      // const formData = new FormData();
      // formData.append('avatar', file.raw,
      //                 'bookname',this.createData.bookname); // 'avatar' 是后端接收文件的字段名，可根据后端接口定义修改
      // console.log(file.raw);
      //
      // axios.post(`http://127.0.0.1:5000/v1/admin/ReceivePic/${bookname}`, formData, {
      //   headers: {
      //     'Content-Type': 'multipart/form-data' // 设置 Content-Type 为 multipart/form-data
      //   }
      // }).then( response=> {
      //   console.log(response)
      //   this.$message({
      //     type: 'success',
      //     message: '上传成功'
      //   });
      // }).catch(() => {
      //   // 处理上传失败后的逻辑，如果需要的话
      // });
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
  },
  mounted() {
    this.getAllCategorys();
  //   发送异步请求获取数据
    axios.get("http://127.0.0.1:5000/v1/books/allBooks").then((result)=> {
      this.fullData = result.data.data;
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.tableData = this.fullData.slice(start, end);
      this.itemNumber = this.fullData.length;
      this.is_admin = Cookies.get('is_admin');
      this.username = Cookies.get('username');
      this.password = Cookies.get('password');
    });
  }
}

</script>

<style scoped>
.avatar-uploader .el-upload {
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}
.avatar {
  width: 80px;
  height: 80px;
  display: block;
}
</style>